package com.gitee.cui.netty.decoder;

import com.gitee.cui.util.RandomUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 字符串解码测试类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 20:48
 **/
public class StringReplayDecoderTest {

    private String value = "这是一个测试字符串";

    @Test
    public void stringReplayDecoderTest() {
        ChannelInitializer<EmbeddedChannel> initializer = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new StringReplayDecoder());
                ch.pipeline().addLast(new StringProcessHandler());
            }
        };
        EmbeddedChannel channel = new EmbeddedChannel(initializer);

        byte[] strBytes = value.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < 100; i++) {
            // 随机循环发送100次
            // 字符串拼接次数
            int rand = RandomUtil.randInMod(3);
            ByteBuf buffer = Unpooled.buffer();
            // 字符串长度
            buffer.writeInt(strBytes.length * rand);
            // 字符串内容，根据次数循环写入
            for (int j = 0; j < rand; j++) {
                buffer.writeBytes(strBytes);
            }
            // 写道入站中
            channel.writeInbound(buffer);
        }

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
